/**
 * Base module of OverFish Framework
 * 
 * @author Tomas Holub
 * @package OverFish
 */
 
/**
 * Framework version.
 */
exports.version = '0.2.5';

/**
 * Module dependencies.
 */
var connect = require('connect'),
    routers = require('./routers').routers,
    model = require('./model'),
    sys = require('sys'),
    fs = require('fs'),
    env = require('./Environment'),
    events = require("events"),
    menuBuilder = require('./menuBuilder');

/**
 * Array of routers
 */
exports.routers = routers
/**
 * Environment
 */
exports.env = env;
/**
 * Response object
 */
exports.response = undefined;

exports.modules = new Array();
exports.initModel = model.init;

/**
 * Function emits controller action
 * 
 * @param {Request} req
 * @param {Array} params  
 */
exports.route = function (req, params) {
  utils = require('./utils');
  
  c =  utils.capitalize(params.module) + 'Module'
            + '/' + params.env
            + '/controllers/' + utils.capitalize(params.controller) + 'Controller';
        
  env.viewDir = env.appDir
        + '/' + utils.capitalize(params.module) + 'Module'
        + '/' + params.env
        + '/templates/' + utils.capitalize(params.controller) + '/';
  
  env.controllers[c].emit(params.action, req);
}

/**
 * Function renders template
 * 
 * @param {String} tpl
 * @param {Array} params  
 */
exports.render = function (tpl, params) {
  fs = require('fs');
  var jazz = require("jazz");
  
  layoutSrc = new String(fs.readFileSync(env.layoutFile));
  template = jazz.compile(layoutSrc);

  params['content_file'] = env.viewDir + tpl + '.html';
  
  
  
  if (env.projectName != undefined)
  {
    params['projectName'] = env.projectName;
  }
  else
  {
    params['projectName'] = '';
  }
  
  params['menu'] = menuBuilder.buildBackendMenu(env.backendMenu);
  
  
  var tmpl = jazz.compile(new String(fs.readFileSync(env.viewDir + tpl + '.html', "utf8")));
  tmpl.eval(params, function (data) {
    params['content'] = data;
    
    template.eval(params, function(body) { 
      exports.response.writeHead(200, {
              'Content-Type': 'text/html',
              'Content-Length': body.length
      });
      
      exports.response.end(body, 'utf8'); 
    });
  });
   
  
  
}

exports.serve = function (port)
{
  moduleLoader = require('./moduleLoader');
  
  moduleLoader.load();
  
  var server = connect.createServer(
    connect.logger({ buffer: true })
  );
  
  /*
   * Initialize routers
   */
  routers.forEach(function (r) {
    server.use('/' + r.namespace + '/', connect.router(r.callback));
  });
  
  server.use(connect.staticProvider(env.publicDir));
  
  /*
   * Start server
   */
  server.listen(port);
  console.log('Connect server listening on port ' + port);
}

